/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
/**
 * 
 */
package org.myontology.view.items;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringEscapeUtils;
import org.myontology.controller.AttributeHolder;
import org.myontology.model.Property;
import org.myontology.model.Subject;
import org.myontology.model.ValidatorException;

import controller.elementMapper.StoredInMeantimeException;
import controller.elementMapper.UriAlreadyExistsException;
import controller.elementMapper.WrongFormatException;

/**
 * @author <a href="michael.hackl@sti2.at">Michael Hackl</a> Project:
 *         Myontology - www.myontology.org STI
 */
public class SingleEditAreaBuilder extends AbstractComponentBuilder {

	/**
	 * @param property
	 * @param builder
	 */
	public SingleEditAreaBuilder(Property property, FormBuilder builder) {
		super(property, builder);
	}

	public String getFormInEditMode(AttributeHolder attributes) {

		String ret = "";
		String actualVersionContent = NOTHINGSELECTED;

		String label = "";

		// TODO: element is a class
		// if( uri!=null ) {
		// String tmp = p.getValueString();
		// if( tmp!=null ) {
		// actualVersionContent = getHTMLContent( tmp );
		// }
		//			
		//
		// label = Mapper.selectLabel( uri, Vocabulary.ENGLISH);
		// if( label==null )
		// label = "";
		// }

		// TODO am I dealing with the right value?
		String entry = property.getValueString();
		String content = displayEditField(entry);

		// TODO: actualVersionContent????
		ret = renderEditForm(attributes, content,"");

		return ret;
	}

	protected String displayEditField(String entry) {
		int rows = 4;
		int cols = 60;
		if (entry == null)
			entry = "";
		else {
			rows = entry.split("\n").length;

			rows += entry.length() / cols;

			rows++;

			if (rows < 4)
				rows = 4;

			entry += " ";
		}

		String content = "<textarea tabindex=\"\" id=\"" + Subject.NAMEFORMELEMENT
				+ property.getKey() + "\" name=\"" + Subject.NAMEFORMELEMENT
				+ property.getKey() + "\" rows=\"" + rows + "\" cols=\"" + cols
				+ "\">" + entry + "</textarea>";

		content += "<div class=\"inputhint\">Free text; do not use any hypertext like HTML!</div>";
		return content;
	}

	protected String renderEditForm(AttributeHolder attributes,String content,
			String actualVersionContent) {

		StringBuilder ret = new StringBuilder();

		if (!property.getDescription(builder.getLocale()).equals("")) {
			ret.append("<div class=\"fieldexplaination\">(").append(
					StringEscapeUtils.escapeHtml(property
							.getDescription(builder.getLocale()))).append(
					")</div>");
		}

		ret.append("<table style=\"width:100%;\"><tr>\n");
		ret.append("<td class=\"fieldnavigation\">\n");

		showNavigation(ret);

		ret.append("</td>\n");
		ret.append("<td class=\"fieldcontentcontainer\">\n");

		boolean showActualValues = false;
		if (builder.getState().equals(FormBuilderStates.EDIT) || builder.getState().equals(FormBuilderStates.EDIT_SINGLE))
			showActualValues = showErrors(ret, attributes);

		if (showActualValues == true) {

			ret.append("<div class=\"alreadystoredheader\">Stored:</div>\n");
			ret
					.append("<div class=\"inputhint\">(Cancel to keep this entry)</div>\n");

			ret.append("<div class=\"fieldcontentmain\">\n");
			ret.append(actualVersionContent);
			ret.append("</div>\n");

			ret
					.append("<div class=\"alreadystoredheader\">Your Input:</div>\n");
			ret
					.append("<div class=\"inputhint\">(Save to override stored entry)</div>\n");
		}

		ret.append("<div class=\"fieldcontentmain\">\n");
		ret.append(content);
		ret.append("</div>\n");

		ret.append("</td>\n");
		ret.append("</tr></table>\n");

		return ret.toString();
	}

	protected boolean showErrors(StringBuilder ret, AttributeHolder attributes) {
		boolean showActualValues = false;
		String errorsDiv = "<div id=\"" + Subject.NAMEFORMELEMENT + property.getKey()
				+ "_errors\">\n";
		String storedInMeantimeError = "";
		List<Exception> exceptions = property.validate(attributes);
		if (exceptions != null) {

			Iterator<Exception> iter = exceptions.iterator();
			while (iter.hasNext()) {

				Exception exception = iter.next();

				if (exception instanceof WrongFormatException
						|| exception instanceof UriAlreadyExistsException) { // exception.getMessage()!=null
																				// ) {

					errorsDiv += "<div class=\"error\">"
							+ exception.getMessage() + "</div>";
				} else if (exception instanceof StoredInMeantimeException) {
					storedInMeantimeError = "<div class=\"error\">"
							+ exception.getMessage() + "</div>";
					showActualValues = true;
				} else if (exception instanceof ValidatorException) {
					ResourceBundle texts = ResourceBundle.getBundle("errors",
							builder.getLocale());
					errorsDiv += "<div class=\"error\">"
							+ texts.getString(exception.getMessage())
							+ "</div>";
				} else {
					errorsDiv += "<div class=\"error\">An unknown exception occured. If you want to help to improve myOntology please contact the webmaster and tell how this exception occured.";
					errorsDiv += exception.getMessage() + "</div>";
				}

			}
		}
		errorsDiv += "</div>\n";

		ret.append(storedInMeantimeError + errorsDiv);
		return showActualValues;

	}

	protected void showNavigation(StringBuilder ret) {
		if (builder.getState().equals(FormBuilderStates.EDIT) || builder.getState().equals(FormBuilderStates.EDIT_SINGLE) ) {
			ret.append("<span style=\"margin-right:7px;\">").append(
					getLinkToUpdate()).append("</span>").append(
					getLinkToClose());
		}
	}

	protected String getLinkToUpdate() {
		//TODO format
		String entry = new Date(property.getVersionDate()).toString();
		String escapedEntry = "";
		if (entry != null)
			escapedEntry = StringEscapeUtils.escapeJavaScript(StringEscapeUtils
					.escapeHtml(entry));
		String ret = "<img style=\"cursor:pointer\" onclick=\"sendpropertyupdaterequest('"
				+ CSSIDFIELD
				+ property.getKey()
				+ "','"
				+ Subject.NAMEFORMELEMENT
				+ property.getKey()
				+ "','"
				+ escapedEntry
				+ "','"
				+ property.getKey()
				+ "');\" src=\"skins/default/images/accept.png\" border=\"0\" title=\"Save and close\" alt=\"Save and close\" id=\""
				+ Subject.NAMEFORMELEMENT + property.getKey() + "_savebutton\" />";
		return ret;
	}

	protected String getLinkToClose() {

		String ret = "<img style=\"cursor:pointer\" onclick=\"this.src='skins/default/images/loading.gif';this.style.cursor='wait';showpropertyinviewmode('"
				+ CSSIDFIELD
				+ property.getKey()
				+ "',false,'"
				+ property.getKey()
				+ "');\" src=\"skins/default/images/cancel.png\" border=\"0\" title=\"Cancel\" alt=\"Cancel\" />";

		return ret;
	}

}
